<!DOCTYPE HTML>
<html>

<head>
  <meta charset="utf-8">
  <link rel="icon" href="https://jscdn.com.cn/highcharts/images/favicon.ico">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <style>

  </style>
  <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
  <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.4/css/select2.min.css" rel="stylesheet" />

  <style>

  </style>
</head>

<body>
  <div id="app">
    <template>
      <div class="grid-content bg-purple-light">
        <el-container>
          <el-header style="margin: 100px 0px">
            <div class="block">
              <span class="demonstration"></span>
              <el-date-picker v-model="selectTime" type="datetimerange" range-separator="至" start-placeholder="开始日期"
                end-placeholder="结束日期" @change="changeTime">
              </el-date-picker>
            </div>
            <el-select v-model="coin" placeholder="请选择">
              <el-option v-for="item in coins" :value="item">
              </el-option>
            </el-select>

            <el-select v-model="interval" placeholder="请选择" @change="selectInterval">
              <el-option v-for="item in intervals" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
            <el-button type="primary" @click="clickQuery()" round>查询</el-button>
          </el-header>
          <el-main>
            <div id="container" class="ml-4" style="width:90%;height:700px">请选择交易对...</div>
          </el-main>
        </el-container>
      </div>
    </template>
  </div>



  <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
  <script src="https://unpkg.com/element-ui/lib/index.js"></script>
  <script type="text/javascript" src="http://cdn.bootcss.com/jquery/1.12.4/jquery.min.js"></script>
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  <script src="https://cdn.bootcdn.net/ajax/libs/dayjs/1.10.6/dayjs.min.js"></script>

  <script src="https://cdn.highcharts.com.cn/highstock/highstock.js"></script>
  <script src="https://cdn.highcharts.com.cn/highcharts/modules/exporting.js"></script>
  <script src="https://code.highcharts.com.cn/highcharts-plugins/highcharts-zh_CN.js"></script>
  <script src="https://cdn.highcharts.com.cn/highcharts/modules/drag-panes.js"></script>
  <script>

    const ohlcMap = new Map()
    const volumeMap = new Map()
    const xx = new Map()
    const times = [1500004800000, 1499990400000, 1499644800000, 1498867200000]
    var app = new Vue({
      el: '#app',
      data() {
        return {
          max: '',
          min: '',
          startTime: '',
          endTime: '',
          timeArr: [],
          radio: '',
          coin: '',
          interval: [1, 'd', 0],
          // pickerOptions: {
          //   shortcuts: [{
          //     text: '最近一周',
          //     onClick(picker) {
          //       const start = dayjs().subtract(7, 'day').valueOf()
          //       picker.$emit('pick', [start, endTime]);
          //       // startTime = 
          //     }
          //   }, {
          //     text: '最近一个月',
          //     onClick(picker) {
          //       const start = dayjs().subtract(30, 'day').valueOf()
          //       picker.$emit('pick', [start, endTime]);
          //     }
          //   }, {
          //     text: '最近三个月',
          //     onClick(picker) {
          //       const start = dayjs().subtract(90, 'day').valueOf()
          //       picker.$emit('pick', [start, endTime]);
          //     }
          //   }, {
          //     text: '最近半年',
          //     onClick(picker) {
          //       const start = dayjs().subtract(6, 'month').valueOf()
          //       picker.$emit('pick', [start, endTime]);
          //     }
          //   }, {
          //     text: '最近一年',
          //     onClick(picker) {
          //       const start = dayjs().subtract(1, 'year').valueOf()
          //       picker.$emit('pick', [start, endTime]);
          //     }
          //   }, {
          //     text: '最近三年',
          //     onClick(picker) {
          //       const start = dayjs().subtract(3, 'year').valueOf()
          //       picker.$emit('pick', [start, endTime]);
          //     }
          //   }]
          // },
          selectTime: [],
          coins: [],
          intervals: [
            { value: [1, 'm', 0], label: "1分钟" },
            { value: [5, 'm', 0], label: "5分钟" },
            { value: [30, 'm', 0], label: "30分钟" },
            { value: [1, 'h', 0], label: "1小时" },
            { value: [6, 'h', 1], label: "6小时" },
            { value: [12, 'h', 1], label: "12小时" },
            { value: [1, 'd', 1], label: "1天" },
            { value: [1, 'w', 2], label: "1周" },
            { value: [1, 'M', 3], label: "1个月" },
          ]
        };
      },
      methods: {
        initSelectTime() {
          console.log(this.interval)
          const end = dayjs(this.selectTime[1]).valueOf()
          const _start = dayjs(this.selectTime[0]).valueOf()
          let start = dayjs(end).subtract(this.interval[0] * 1000, this.interval[1]).valueOf()
          start = start >= _start ? start : _start
          console.log(`start = ${start}`)
          start = start >= times[this.interval[2]] ? start:  times[this.interval[2]]
          console.log(` times[this.interval[2]] = ${times[this.interval[2]]}`)
          console.log(start)
          this.selectTime = [start, end]
        },
        selectInterval() {
          // console.log(this.interval)
          this.initSelectTime()
          // this.getTime2()
        },
        changeTime() {
          this.initSelectTime()
          this.getTime2()
        },
        getAllCoin() {
          axios.get('/getAllCoin').then(res => {
            this.coins = res.data
          })
        },
        getTime() {
          ohlcMap.clear()
          volumeMap.clear()
          const interval = this.interval.replace(',', '')
          const start = dayjs(this.selectTime[0]).valueOf()
          const end = dayjs(this.selectTime[1]).valueOf()
          axios.get('/getKlinesTime', { params: { 'symbol': 'ETHBTC', 'interval': interval, startTime: start, endTime: end, limit: 1000 } }).then(data => {
            data = data.data
            for (const item of data) {
              ohlcMap.set(item, [null, 0, 0, 0])
              volumeMap.set(item, [0])
              this.timeArr.push(item)
            }
            console.log(ohlcMap)
          })

        },
        //按照时间范围，显示合理的时间间隔
        initInterval() {
          const intervals = [
            { value: [1, 'm', 0], label: "1分钟" },
            { value: [5, 'm', 0], label: "5分钟" },
            { value: [30, 'm', 0], label: "30分钟" },
            { value: [1, 'h', 0], label: "1小时" },
            { value: [6, 'h', 1], label: "6小时" },
            { value: [12, 'h', 1], label: "12小时" },
            { value: [1, 'd', 1], label: "1天" },
            { value: [1, 'w', 2], label: "1周" },
            { value: [1, 'M', 3], label: "1个月" },
          ]
          this.intervals = []
          //时间间隔的毫秒值
          const timeArr = [60000, 300000, 1800000, 3600000, 21600000, 43200000, 86400000,
            604800000, 1296000000, 2592000000, 15552000000, 31536000000]

          //时间差毫秒值
          const timeDiff = this.selectTime[1] - this.selectTime[0]

          if (timeDiff < 60000) {
            this.$message({ message: "时间范围不能小于1分钟", type: 'warning' })
            this.selectTime[1] = dayjs(this.selectTime[0]).add(1, 'm')
          }

          //过滤，得到符合的数组
          let arr = timeArr.filter(item => {
            return timeDiff >= item
          })
          let index = arr.length - 1
          arr = []
          //根据arr数组的长度作为index 来取出intervals
          do {
            arr.push(intervals[index])
          } while (index--);
          this.intervals = arr.reverse()
          const selectInterval = this.intervals.filter(item => {
            return item.value == this.interval
          })
          this.interval = selectInterval.length == 0 ? this.intervals[0].value : this.interval
        },
        chart() {

          var ohlc = []
          volume = []
          ohlcMap.forEach((value, key) => {
            ohlc.push([key].concat(value))
          });
          volumeMap.forEach((value, key) => {
            volume.push([key].concat(value))
          });
          Highcharts.stockChart('container', {
            chart: {
              type: 'candlestick',
              zoomType: 'x'
            },
            navigator: {
              adaptToUpdatedData: false,
              series: {
                data: ohlc
              }
            },
            scrollbar: {
              liveRedraw: false
            },
            tooltip: {
              split: false,
              shared: true,
            },
            title: {
              text: app.coin
            },
            xAxis: {
              max: app.max,
              min: app.min,
              adaptToUpdatedData: false,
              events: {
                afterSetExtremes: this.afterSetExtremes
              }
            },
            yAxis: [{
              labels: {
                align: 'right',
                x: -3
              },
              title: {
                text: '股价'
              },
              height: '75%',
              resize: {
                enabled: true
              },
              lineWidth: 2
            }, {
              labels: {
                align: 'right',
                x: -3
              },
              title: {
                text: '成交量'
              },
              top: '75%',
              height: '25%',
              offset: 0,
              lineWidth: 2
            }],
            series: [{
              lineColor: 'green',
              upLineColor: 'red',
              upColor: 'red',
              color: 'green',
              data: ohlc,
              dataGrouping: {
                enabled: false
              }
            }, {
              type: 'column',
              data: volume,
              yAxis: 1,
              dataGrouping: {
                enabled: false
              }
            }]
          })
        },
        clickQuery() {
          let start = dayjs(this.selectTime[1]).subtract(30, this.intervalData).valueOf()
          start = start > dayjs(this.selectTime[0]).valueOf() ? start : dayjs(this.selectTime[0]).valueOf()
          this.max = this.selectTime[1]
          this.min = start
          this.getKlines(start, dayjs(this.selectTime[1]).valueOf())
        },
        afterSetExtremes(e) {
          var min = Math.ceil(e.min)
          var max = Math.ceil(e.max)
          app.max = max
          app.min = min
          const interval = app.interval.replace(',', '')

          let arr = (app.timeArr).filter(item => {
            return min <= item && max >= item
          })

          arr = arr.filter(item => {
            return ohlcMap.get(item)[0] == null
          })

          if (arr.length) {
            app.getKlines(arr[0], arr[arr.length - 1])
          }
        },
        getKlines(start, end) {
          const interval = this.interval.replace(',', '')
          axios.get('/klines', { params: { 'symbol': app.coin, 'interval': interval, startTime: start, endTime: end, limit: 1000 } }).then(data => {
            data = data.data
            for (const item of data) {
              ohlcMap.set(item[0], [Number(item[1]), Number(item[2]), Number(item[3]), Number(item[4])])
              volumeMap.set(item[0], [Number(item[5])])
            }
            console.log(ohlcMap)
            this.chart()
          })
        },
        getTime2() {
          xx.clear()
          let start = dayjs(this.selectTime[0]).set('second', 0).set('millisecond', 0).valueOf()
          let end = dayjs(this.selectTime[1]).set('second', 0).set('millisecond', 0).valueOf()
          if (this.intervalData == 'm') {
            const min = dayjs(start).minute() % this.intervalNum
            start = min == 0 ? start : dayjs(start).add(this.intervalNum - min, this.intervalData).valueOf()
            this.initTime(start, end)
          } else {
            start = dayjs(start).set('minute', 0).hour(8).valueOf()
            this.initTime(start, end)
            console.log(xx)
          }
        },
        initTime(start, end) {
          while (true) {
            xx.set(start, null)
            start = dayjs(start).add(this.interval[0], this.interval[1]).valueOf()
            if (start >= end) break
          }
        }
      },
      created() {
        this.getAllCoin()
        this.selectTime = [dayjs().subtract(this.interval[0] * 1000, this.interval[1]).valueOf(), dayjs().valueOf()]
        // this.getTime2()
        // this.getTime()
        console.log(this.interval)
      }
    })

  </script>
</body>

</html>